package com.zghl.controller;

import com.zghl.pojo.Equipment;
import com.zghl.pojo.Unit;
import com.zghl.service.UnitService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/unit")
public class UnitController {
    @Resource
    private UnitService unitService;

    @RequestMapping("/getList")
    public ModelAndView getList(){
        List<Unit> units = unitService.UnitList(null);

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("unitList");
        modelAndView.addObject("list",units);

        return modelAndView;
    }

    @RequestMapping("/add")
    public ModelAndView add(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("unitAdd");

        Unit unit=new Unit();
        modelAndView.addObject("unit",unit);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/save")
    public ModelAndView addUnit(@ModelAttribute Unit unit){
        Integer integer = unitService.AddByUnit(unit);

        if (integer>0){
            return getList();
        }
        throw  new RuntimeException("添加错误");
    }

    @RequestMapping("/delete/{unitId}")
    public ModelAndView deleteUnit(@PathVariable("unitId") int unitId){
        Integer integer = unitService.deleteByUnit(unitId);

        if (integer>0){
            return getList();
        }
        throw  new RuntimeException("删除错误");
    }

    @RequestMapping("/update/{unitId}")
    public ModelAndView update(@PathVariable("unitId") int unitId){

        Map<String,Object> map=new HashMap<>();

        map.put("id",unitId);

        List<Unit> units = unitService.UnitList(map);

        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("unitUpdate");

        Unit unit=new Unit();

        for ( Unit u:units) {
            BeanUtils.copyProperties(u,unit);
        }
        modelAndView.addObject("un",unit);
        modelAndView.addObject("unitId",unitId);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/updateSvae/{unitId}")
    public ModelAndView updateUnit(@PathVariable("unitId") int unitId,@ModelAttribute Unit unit){
        Unit unit1=new Unit();

        BeanUtils.copyProperties(unit,unit1);
        unit1.setId(unitId);

        Integer integer = unitService.updateByUnit(unit1);
        if (integer>0){
            return getList();
        }
        throw  new RuntimeException("添加错误");
    }
}
